package com.northwest_man.refactor_tool;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 扫描目录下的java文件并复制这些文件import的其它java文件
 * 若复制进来的java文件import了新的文件就继续复制，直到该目录下的文件不再依赖新的java文件
 */
abstract class MigrateJavaFileRecursively {

    static final String toPath = "/Users/yong.hu/AndroidStudioProjects/patpat/module_check_in/src/main/java";
    static final String fromPath = "/Users/yong.hu/AndroidStudioProjects/patpat/Patpat/src/main/java";
    static final boolean printStackTrace = true;

    public static void main() {
        int time = 1;
        while (true) {
            final boolean newFileCopied = cp();
            System.out.printf("%s\n%d：本次循环有没有新增文件：%s\n%s\n",
                    "---------------------------------------------------",
                    time++,
                    newFileCopied + "",
                    "---------------------------------------------------");
            if (!newFileCopied) break;
        }
    }

    public static boolean cp() {
        final File root = new File(toPath);

        return cp2(root);
    }

    private static boolean cp2(File root) {
        if (root.isDirectory()) {
            final File[] fileArr = root.listFiles();
            if (fileArr == null) return true;
            boolean newFileCopied = false;
            for (File file : fileArr) {
                if (file.isDirectory()) {
                    final boolean newFileCopied2 = cp2(file);
                    if (newFileCopied2) newFileCopied = true;
                } else {
                    final boolean newFileCopied2 = cp3(file);
                    if (newFileCopied2) newFileCopied = true;
                }
            }
            return newFileCopied;
        } else {
            return cp3(root);
        }
    }

    /**
     * @return 复制了新文件进来所以需要再对新复制进来的文件进行遍历
     */
    private static boolean cp3(final File file) {

        final String fileContent;
        try {
            fileContent = FileUtils.readFileToString(file, Charset.defaultCharset());
        } catch (IOException e) {
            if (printStackTrace) e.printStackTrace();
            return false;
        }
//        final String regex = "import\\s*(com.interfocusllc.patpat.[^;]+)\\s;";
        // import\s+([.a-zA-Z0-9_]+?)\s*;
        final String regex = "import\\s+([.a-zA-Z0-9_]+?)\\s*;";
        final Pattern pattern = Pattern.compile(regex);

        final Matcher matcher = pattern.matcher(fileContent);

        final StringBuilder stringBuilder = new StringBuilder();
        boolean newFileCopied = false;
        while (matcher.find()) {
            if (matcher.group().matches("import\\s+com.interfocusllc.patpat.R\\s*;")) continue;
            if (matcher.group().matches("import\\s+com.interfocusllc.patpat.BuildConfig\\s*;"))
                continue;
            final String item = matcher.group(1);
            try {
                final File fromFolder = new File(fromPath + "/" + item.substring(0, item.lastIndexOf(".")).replace('.', '/'));
                if (!fromFolder.isDirectory()) {
                    // 如果某个import语句为某个类的内部类，则需要筛掉这部分的import语句，不需要复制这部分的文件，也找不到这部分的文件
                    // 1. com.interfocusllc.patpat.ui.membershipbenfits.bean.NewMembershipBean.Benefit
                    // 2. com.interfocusllc.patpat.dialog.PromptDialog.IDismissCallback
                    // 3. com.interfocusllc.patpat.widget.FixListView.OnShowListener
                    // 4. com.interfocusllc.patpat.utils.PatUriParser.ActionInfo
                    // 5. com.interfocusllc.patpat.ui.membershipbenfits.bean.NewMembershipBean.Benefit
                    continue;
                }
            } catch (Exception e) {
                System.out.println(matcher.group());
                e.printStackTrace();
                continue;
            }
            final File toFile = new File(toPath + "/" + item.replace('.', '/') + ".java");
            if (toFile.exists()) continue;
            try {
                FileUtils.copyFile(new File(fromPath + "/" + item.replace('.', '/') + ".java"), new File(toPath + "/" + item.replace('.', '/') + ".java"));
                newFileCopied = true;
            } catch (IOException e) {
                stringBuilder.append(item).append("\n");
                if (printStackTrace) e.printStackTrace();
            }

        }
        if (stringBuilder.length() > 0) {

            System.out.println("以下文件复制失败：");
            System.out.println(stringBuilder);
        }
        return newFileCopied;

    }
}
